package com.example.zzmftp.service.impl;

import com.example.zzmftp.config.FtpProperties;
import com.example.zzmftp.service.ZzmFtpService;
import com.example.zzmftp.util.FtpHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;

/**
 * @Author zzm
 * @Date 2023/4/7 14:47
 * @Version 1.0
 * @Description ftp操作
 */
@Component
public class ZzmFtpServiceImpl implements ZzmFtpService {

    @Autowired
    private FtpProperties ftpProperties;

    @Override
    public String uploadFile(MultipartFile file){
        try {
            FtpHelper ftpHelper = new FtpHelper(ftpProperties);
            InputStream stream = file.getInputStream();
            return ftpHelper.uploadFile(stream, file.getOriginalFilename(), ftpProperties.getPathUrl());
        }catch (Exception e){
            e.printStackTrace();
        }
        return "error";
    }
    @Override
    public void downloadFile(String filePath, HttpServletResponse response){
        FtpHelper ftpHelper = new FtpHelper(ftpProperties);
        try {
            InputStream fis = ftpHelper.downloadFile(filePath);
            //将输入流的事件写出到输出事件
            ServletOutputStream sos = response.getOutputStream();
            byte[] buffer = new byte[1024 * 8];
            int length = 0;
            while((length = fis.read(buffer)) != -1){
                sos.write(buffer,0,length);
            }
            sos.close();
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    @Override
    public void deleteFile(String filePath){
        FtpHelper ftpHelper = new FtpHelper(ftpProperties);
        try {
            ftpHelper.deleteFile(filePath);
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
